package com.chdwmp.product.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.chdwmp.product.bean.app.Activation;
import com.chdwmp.product.bean.app.AppSystemInfoAdd;
import com.chdwmp.product.bean.app.SerialNumberInfo;
import com.chdwmp.product.constant.ApplicationProperties;
import com.chdwmp.product.constant.Status;
import com.chdwmp.product.exception.CommonException;
import com.chdwmp.product.mapper.AppMapper;
import com.chdwmp.product.mapper.SerialNumberMapper;
import com.chdwmp.product.service.SerialNumberService;
import com.chdwmp.product.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Auther: LLL
 * @Date: 2021/3/29 21:09
 * @Description:
 */
@Service
public class SerialNumberServiceImpl implements SerialNumberService {

    @Autowired
    SerialNumberMapper serialNumberMapper;
    @Autowired
    AppMapper appMapper;
    @Autowired
    ApplicationProperties applicationProperties;

    @Override
    @Transactional
    public SerialNumberInfo getTestSerialNumbers(String imei) {
        SerialNumberInfo serialNumber = serialNumberMapper.getTestSerialNumbers();
        if(null !=  serialNumber){
            serialNumberMapper.updateTestServiceNumber(serialNumber.getId());
            //做一次保活记录
            appMapper.addAppKeepLived(imei, serialNumber.getSerialNumber());
            return serialNumber;
        }else{
            throw new CommonException(Status.NO_TEST_SERIAL_NUMBER);
        }

    }

    @Override
    @Transactional
    public void recoverySerialNumber(String imei, String number) {
        serialNumberMapper.updateTestServiceNumberByRecovery(number);
        //如果5分钟内没有保活记录，也回收
        Date current_date = new Date();
        String create_time = serialNumberMapper.queryCurrentKeepLivedCreateTime(imei);
        if (StrUtil.isNotEmpty(create_time)) {
            Date create_time_date = DateUtil.parse(create_time);
            if (DateUtil.betweenMs(create_time_date, current_date) > 300000) {
                serialNumberMapper.updateTestServiceNumberByRecovery(number);
            }
        }
    }

    @Override
    @Transactional
    public Activation activationSerialNumber(Activation activation) {
        Activation activation_result = new Activation();
        String number = null;

        // 查询供应商是否购买过产品
        List<Integer> agent_id = serialNumberMapper.queryAgentIdByName(activation.getFirst_class_customer_name());
        String tempId = null;
        if(null != agent_id){
            tempId = StringUtil.formatListToInteger1(agent_id);
        }
        int buy_count = serialNumberMapper.queryAgentIsBuyProduct(tempId, activation.getProduct_id());
        if (buy_count > 0) {
            //查询设备表里 imei是否已经激活，即有没有记录
            int conut1 = serialNumberMapper.queryImeiIsExits(activation.getImei());
            if (conut1 > 0) {
                int count2 = serialNumberMapper.queryProductIsExits(activation.getProduct_id(),activation.getImei());
                //判断设备表里这个产品是否存在 如果存在 返回已激活的信息
                if (count2 > 0) {
                    activation_result.setStatus(1);
                    activation_result.setPhone(activation.getPhone());
                    activation_result.setImei(activation.getImei());
                    activation_result.setPassword(activation.getPhone());
                    activation_result.setPrefix_code(activation.getPrefix_code());
                    activation_result.setSerial_number(serialNumberMapper.querySerialNumberByImei(activation.getImei()));
                    activation_result.setProduct_id(activation.getProduct_id());
                    activation_result.setFirst_class_customer_name(activation.getFirst_class_customer_name());
                    activation_result.setSecond_class_customer_name(activation.getSecond_class_customer_name());
                    activation_result.setCreate_time(serialNumberMapper.queryCreateTimeBySeriaNumber(activation_result.getSerial_number()));
                    activation_result.setIp_addr(applicationProperties.ip_addr);
                    List<String> productids = serialNumberMapper.queryBindProductIdList(activation.getImei());
                    activation_result.setProductIds(productids);
                    return activation_result;
                }else{
                    String agentName = serialNumberMapper.queryAgentIdByName1(activation.getImei());
                    if (StrUtil.isNotEmpty(agentName) && agentName.equals(activation.getFirst_class_customer_name())) {
                        Integer agentId = appMapper.queryAgentBuyProductId(activation.getFirst_class_customer_name(), activation.getProduct_id());
                        int count = appMapper.queryBuyCount(activation.getProduct_id(),agentId);
                        if(count > 0){
                            //删除  已激活的代理商删掉 代理商和产品中间表
                            appMapper.deleteAgentProductRelation(agentId, activation.getProduct_id());
                            //
                            activation_result.setStatus(0);

                            StringBuilder stringBuilder = new StringBuilder();
                            List<String> productids = null;
                            productids = serialNumberMapper.queryBindProductIdList(activation.getImei());
                            String s = StringUtil.formatListToString6(productids);
                            if(StrUtil.isNotEmpty(s)){
                                stringBuilder.append(s).append(",").append(activation.getProduct_id());
                                serialNumberMapper.updateProductIdByImei(stringBuilder.toString(),activation.getImei());
                            }
                            activation_result.setPhone(activation.getPhone());
                            activation_result.setImei(activation.getImei());
                            activation_result.setPassword(activation.getPhone());
                            activation_result.setPrefix_code(activation.getPrefix_code());
                            activation_result.setSerial_number(serialNumberMapper.querySerialNumberByImei(activation.getImei()));
                            activation_result.setProduct_id(activation.getProduct_id());
                            activation_result.setFirst_class_customer_name(activation.getFirst_class_customer_name());
                            activation_result.setSecond_class_customer_name(activation.getSecond_class_customer_name());
                            activation_result.setCreate_time(serialNumberMapper.queryCreateTimeBySeriaNumber(activation_result.getSerial_number()));
                            activation_result.setIp_addr(applicationProperties.ip_addr);
                            productids = serialNumberMapper.queryBindProductIdList(activation.getImei());
                            activation_result.setProductIds(productids);
                            return activation_result;
                        }else {
                            activation_result.setStatus(-1);
                            return activation_result;
                        }


                    }else{
                        activation_result.setStatus(-2);
                        activation_result.setPhone(activation.getPhone());
                        activation_result.setImei(activation.getImei());
                        activation_result.setPassword(activation.getPhone());
                        activation_result.setPrefix_code(activation.getPrefix_code());
                        activation_result.setSerial_number(serialNumberMapper.querySerialNumberByImei(activation.getImei()));
                        activation_result.setProduct_id(activation.getProduct_id());
                        activation_result.setFirst_class_customer_name(activation.getFirst_class_customer_name());
                        activation_result.setSecond_class_customer_name(activation.getSecond_class_customer_name());
                        activation_result.setCreate_time(serialNumberMapper.queryCreateTimeBySeriaNumber(activation_result.getSerial_number()));
                        activation_result.setIp_addr(applicationProperties.ip_addr);
                        List<String> productids = serialNumberMapper.queryBindProductIdList(activation.getImei());
                        activation_result.setProductIds(productids);
                        return activation_result;
                    }
                }
            }else{
                //删除  已激活的代理商删掉 代理商和产品中间表
                Integer agentId = appMapper.queryAgentBuyProductId(activation.getFirst_class_customer_name(), activation.getProduct_id());
                int count = appMapper.queryBuyCount(activation.getProduct_id(),agentId);
                if(count > 0){
                    appMapper.deleteAgentProductRelation(agentId, activation.getProduct_id());

                    //从激活那边找一个激活码，添加到app——user里，并打上  是激活码激活的标识
                    number = serialNumberMapper.queryActivationSerialNumber();
                    if(!StrUtil.isEmpty(number)){
                        //把状态改成已使用过
                        serialNumberMapper.updateActivationStatus(number);

                        AppSystemInfoAdd appSystemInfoAdd = new AppSystemInfoAdd();
                        appSystemInfoAdd.setIpaddr(applicationProperties.ip_addr);
                        appSystemInfoAdd.setImei(activation.getImei());
                        appSystemInfoAdd.setPhone(activation.getPhone());
                        appSystemInfoAdd.setPrefixCode(activation.getPrefix_code());
                        appSystemInfoAdd.setFirstClassCustomerName(activation.getFirst_class_customer_name());
                        appSystemInfoAdd.setSecondClassCustomerName(activation.getSecond_class_customer_name());
                        appSystemInfoAdd.setPassword(activation.getPassword());
                        appSystemInfoAdd.setIsActivationCode("1");
                        appSystemInfoAdd.setSerialNumber(number);//把查出来的激活码赋给入库的实体
                        appSystemInfoAdd.setProductId(activation.getProduct_id());
                        appSystemInfoAdd.setActivationaryTime(LocalDateTime.now().toString());
                        appMapper.addAppSystemInfo(appSystemInfoAdd);
                        activation_result.setPhone(activation.getPhone());
                        activation_result.setImei(activation.getImei());
                        activation_result.setPassword(activation.getPhone());
                        activation_result.setPrefix_code(activation.getPrefix_code());
                        activation_result.setSerial_number(number);
                        activation_result.setProduct_id(activation.getProduct_id());
                        activation_result.setFirst_class_customer_name(activation.getFirst_class_customer_name());
                        activation_result.setSecond_class_customer_name(activation.getSecond_class_customer_name());
                        activation_result.setCreate_time(serialNumberMapper.queryCreateTimeBySeriaNumber(appSystemInfoAdd.getSerialNumber()));
                        activation_result.setIp_addr(applicationProperties.ip_addr);
                        activation_result.setStatus(0);
                        List<String> productids = serialNumberMapper.queryBindProductIdList(activation.getImei());
                        activation_result.setProductIds(productids);
                        return activation_result;
                    }else{
                        activation_result.setStatus(-3);
                        return activation_result;
                    }
                }else{
                    activation_result.setStatus(-1);
                    return activation_result;
                }
            }

        }else{
            int conut1 = serialNumberMapper.queryImeiIsExits(activation.getImei());
            if (conut1 > 0) {
                activation_result.setStatus(1);
                activation_result.setPhone(activation.getPhone());
                activation_result.setImei(activation.getImei());
                activation_result.setPassword(activation.getPhone());
                activation_result.setPrefix_code(activation.getPrefix_code());
                activation_result.setSerial_number(serialNumberMapper.querySerialNumberByImei(activation.getImei()));
                activation_result.setProduct_id(activation.getProduct_id());
                activation_result.setFirst_class_customer_name(activation.getFirst_class_customer_name());
                activation_result.setSecond_class_customer_name(activation.getSecond_class_customer_name());
                activation_result.setCreate_time(serialNumberMapper.queryCreateTimeBySeriaNumber(activation_result.getSerial_number()));
                activation_result.setIp_addr(applicationProperties.ip_addr);
                List<String> productids = serialNumberMapper.queryBindProductIdList(activation.getImei());
                activation_result.setProductIds(productids);
                return activation_result;
            } else {
                activation_result.setStatus(-1);
                return activation_result;
            }

        }
    }
}
